package taskTracker.ui.lite;

import javax.microedition.lcdui.Image;

public class List extends javax.microedition.lcdui.List {

	private Object[] dataElements;

	public List(String title, int listType) {
		this(title, listType, new Object[0], null);
	}

	public List(String title, int listType, Object[] dataElements,
			Image[] imageElements) {
		super(title, listType, new String[dataElements == null ? 0 : dataElements.length], imageElements);
		if (dataElements != null)
			for (int elementNum=0; elementNum < dataElements.length;elementNum++)
				super.append(mapToString(dataElements[elementNum]), imageElements==null? null : imageElements[elementNum]);
		this.dataElements = dataElements;
	}
	
	protected String mapToString(Object dataPart) {
		return dataPart == null ? null : dataPart.toString();
	}

	public Object getSelectedObject() {
		return dataElements!=null && super.getSelectedIndex() != -1 ? dataElements[super.getSelectedIndex()] : null;
	}

	/**
	 * Returns the index of the given object
	 * @param dataPart
	 * @return
	 */
	public int indexOf(Object dataPart) {
		for (int i=0;i<this.dataElements.length;i++)
			if (this.dataElements[i].equals(dataPart)) {
				return i;
			}
		return -1;
	}

	public Object getObject(int i) {
		return dataElements[i];
	}
	
	public int append(Object dataPart, Image imagePart) {
		int x = super.append(mapToString(dataPart), imagePart);
		Object[] newElements = new Object[size()];
		if (dataElements != null)
			System.arraycopy(dataElements, 0, newElements, 0, dataElements.length);
		newElements[x] = dataPart;
		dataElements = newElements;
		return x;
	}
	
	public void delete(int elementNum) {
		super.delete(elementNum);
		if (size() == 0) {
			dataElements = null;
			return;
		}
		Object[] newElements = new Object[size()];
		System.arraycopy(dataElements, 0, newElements, 0, elementNum);
		System.arraycopy(dataElements, elementNum+1, newElements, elementNum, size() - elementNum);
	}
	
	public void deleteAll() {
		super.deleteAll();
		this.dataElements = null;
	}

	public void set(int elementNum, Object dataPart, Image imagePart) {
		super.set(elementNum, mapToString(dataPart), imagePart);
		dataElements[elementNum] = dataPart;
	}
	
}
